<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="logo">
        <h2>ColdEatRabbit 溯源系统</h2>
      </div>
      <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" prefix-icon="User" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" prefix-icon="Lock" type="password" placeholder="请输入密码"
                  @keyup.enter="handleLogin"></el-input>
        </el-form-item>
        <el-form-item prop="captchaCode">
          <div class="captcha-container">
            <el-input v-model="loginForm.captchaCode" placeholder="请输入验证码"></el-input>
            <img 
              v-if="captchaUrl" 
              :src="getFullCaptchaUrl(captchaUrl)" 
              class="captcha-image" 
              @click="refreshCaptcha"
              alt="验证码"
            />
            <div v-else class="captcha-loading" @click="refreshCaptcha">
              <el-icon><Loading /></el-icon> 加载中...
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" class="login-button" @click="handleLogin">
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Loading } from '@element-plus/icons-vue'
import { useUserStore } from '../stores/user'
import { login, getCaptcha } from '../api/auth'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const loginFormRef = ref(null)
const captchaUrl = ref('')

// 表单数据
const loginForm = reactive({
  username: 'admin',
  password: '123456',
  captchaCode: '',
  captchaId: ''
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  captchaCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

// 获取验证码
const refreshCaptcha = async () => {
  try {
    console.log('正在获取验证码...')
    
    // 设置加载状态
    captchaUrl.value = ''
    
    const res = await getCaptcha()
    console.log('验证码响应:', res)
    
    if ((res.code === 0 || res.code === 'Success' || res.code === 200) && res.data) {
      captchaUrl.value = res.data.ImageUrl || res.data.imageUrl
      loginForm.captchaId = res.data.CaptchaId || res.data.captchaId
      console.log('设置验证码URL:', captchaUrl.value)
      console.log('设置验证码ID:', loginForm.captchaId)
    } else {
      console.error('获取验证码响应异常:', res)
      ElMessage.error('获取验证码失败')
      captchaUrl.value = ''
    }
  } catch (error) {
    console.error('获取验证码出错:', error)
    ElMessage.error('获取验证码失败，请稍后重试')
    captchaUrl.value = ''
  }
}

// 处理验证码URL
const getFullCaptchaUrl = (url) => {
  if (!url) return ''
  console.log('处理图片URL:', url)
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  const baseUrl = 'http://localhost:5203'
  const fullUrl = `${baseUrl}${url.startsWith('/') ? '' : '/'}${url}`
  console.log('拼接后的完整URL:', fullUrl)
  return fullUrl
}

// 登录处理函数
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    // 表单验证
    await loginFormRef.value.validate()
    
    loading.value = true
    console.log('登录参数:', loginForm)
    
    // 调用登录API
    const res = await login(loginForm)
    console.log('登录响应:', res)
    
    if ((res.code === 0 || res.code === 'Success' || res.code === 200) && res.data) {
      // 登录成功，保存token
      userStore.setToken(res.data)
      
      // 获取用户信息
      const userInfo = await userStore.fetchUserInfo()
      
      if (userInfo) {
        ElMessage.success(`登录成功，欢迎回来，${userInfo.username || ''}`)
        
        // 跳转到首页或之前尝试访问的页面
        const redirect = router.currentRoute.value.query.redirect || '/'
        router.push(redirect)
      }
    } else {
      // 登录失败，刷新验证码
      ElMessage.error(res.message || '登录失败')
      refreshCaptcha()
    }
  } catch (error) {
    console.error('登录出错:', error)
    ElMessage.error(error.message || '登录失败，请稍后重试')
    refreshCaptcha()
  } finally {
    loading.value = false
  }
}

// 页面加载时获取验证码
onMounted(() => {
  refreshCaptcha()
})
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8eb 100%);
}

.login-card {
  width: 400px;
  padding: 20px 20px 30px 20px;
  border-radius: 8px;
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.1);
}

.logo {
  text-align: center;
  margin-bottom: 30px;
}

.logo h2 {
  margin: 0;
  color: #409EFF;
}

.login-form {
  margin-top: 20px;
}

.login-button {
  width: 100%;
}

.captcha-container {
  display: flex;
  align-items: center;
}

.captcha-image {
  margin-left: 10px;
  height: 38px;
  width: 120px;
  cursor: pointer;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s;
}

.captcha-image:hover {
  transform: scale(1.02);
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
}

.captcha-loading {
  margin-left: 10px;
  height: 38px;
  width: 120px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  color: #909399;
}
</style> 